package com.polytech.diploma.SQLGenerator.Oracle.DBEntityGenerators;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.polytech.diploma.DBTablesHelper.DBTablesHelper;
import com.polytech.diploma.DBTablesHelper.DBEntities.CHTable;
import com.polytech.diploma.SQLGenerator.Oracle.Arguments.DataType;
import com.polytech.diploma.SQLGenerator.Oracle.Statements.Table;

public class CTGenerator implements Serializable{

	private static long serialVersionUID = 1L;
	private transient static CTGenerator ctGenerator = null;
	private transient DBTablesHelper dbTablesHelper = null;
	
	private CTGenerator(DBTablesHelper dbTablesHelper)
	{
		this.dbTablesHelper = dbTablesHelper;
	}
	
	public static CTGenerator getInstance(DBTablesHelper dbTablesHelper)
	{
		if (ctGenerator == null)
			ctGenerator = new CTGenerator(dbTablesHelper);
		return ctGenerator;
	}
	
	public List<CHTable> generateCT(Table mp)
	{
		List<CHTable> chTableList = new ArrayList<CHTable>();
		
		Map<String, List<String>> fieldMap = new HashMap<String, List<String>>();
		
		fieldMap = mp.getTablesWithFields(fieldMap);
		for(String tableName : fieldMap.keySet())
		{
			CHTable chTable = new CHTable();
			String result = new String();
			List<String> fieldList = fieldMap.get(tableName);
			
			chTable.setChTable("CT_"+tableName+"_"+serialVersionUID);
			result += "CREATE TABLE " + chTable.getChTable() + "(\r\n";
			serialVersionUID++;
			
			if(fieldList != null)
			{
				for(String field : fieldList)
				{
					DataType type = dbTablesHelper.searchFieldType(tableName, field);
					int precision = dbTablesHelper.searchFieldPrecision(tableName, field);
					
					result += field + "_NEW " + type;
					
					switch (type) {
					case NUMBER:
					case CHAR:
					case VARCHAR2:
						result += "(" + precision + ")";
						break;
					default:
						break;
					}
					
					result += ", " + field + "_OLD " + type;
					
					switch (type) {
					case NUMBER:
					case CHAR:
					case VARCHAR2:
						result += "(" + precision + ")";
						break;
					default:
						break;
					}
					
					result += ", ";
				}
			}			
			result += "opType VARCHAR(1));\r\n";
			chTable.setSqlCreateScript(result);
			chTable.setSqlDropScript("DROP TABLE "+chTable.getChTable()+";\r\n");
			chTableList.add(chTable);
		}	
		
		return chTableList;
	}
}
